package com.file.tool.utils.world;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.PictureRenderData;
import com.deepoove.poi.data.Pictures;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.file.tool.utils.pdf.PDFUtil;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wanglulu
 * @description:
 * @date 2023/01/30 14:58
 * <p>
 * 使用说明： 控制获取系统配置参数 文件路径前缀
 * 配置表 sys_plugin_parameters  默认配置 ： windows c:/claimDoc  linux：/usr/etc/claimDoc
 * <p>
 * 调用方法使用一下代码获取 文件路径前缀
 * String filePathType = "gen.claim.file.win";
 * if (null != System.getProperties().getProperty("os.name")
 * && System.getProperties().getProperty("os.name").toLowerCase().contains("linux")) {
 * filePathType = "gen.claim.file.linux";
 * }
 * String prefixPath = ConfigHelper.getPluginConfig(filePathType, "gen");
 */
public class WorldUtil {

    /**
     * world模板存储文件夹路径  例如： windows c:/claimDoc/world/templates/模板文件  linux：/usr/etc/claimDoc/world/templates/模板文件
     */
    private static final String templatesPath = "/world/templates/";

    /**
     * world生成临时文件夹路径  例如： windows c:/claimDoc/world/temporary/生成文件  linux：/usr/etc/claimDoc/world/temporary/生成文件
     */
    private static final String temporaryPath = "/world/temporary/";

    /**
     * pdf生成临时文件夹路径  例如： windows c:/claimDoc/pdf/temporary/生成文件  linux：/usr/etc/claimDoc/pdf/temporary/生成文件
     */
    private static final String temporaryPathPDF = "/pdf/temporary/";


    public static void main(String[] args) throws IOException {
        String prefixPath = System.getProperty("user.dir");
        System.out.println(prefixPath);
        test(prefixPath);
    }

    /**
     * 测试导出world
     *
     * @param prefixPath
     */
    public static void test(String prefixPath) throws IOException {
        String tempPathPrefix = prefixPath + "\\src\\main\\java\\com\\file\\tool\\utils\\world\\temp\\";
        String tempPath = tempPathPrefix;
        String outFileName = System.currentTimeMillis() + "";
        String outFilePath = tempPathPrefix;
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("title", "测试test咳咳");
        Map<String, Object> user = new HashMap<String, Object>();
        user.put("name", "段然涛");
        user.put("sex", "男");
        user.put("birthday", "1994-03-14");
        user.put("phone", "17737138812");
        user.put("address", "河南省许昌市");
        user.put("school", "江西科技师范大学");
        data.put("user", user);
        List<StudentDemo> educations = new ArrayList<StudentDemo>();
        educations.add(new StudentDemo("1", "姜中", "200809", "201207", "keke", Pictures.ofLocal(tempPathPrefix + "1.jpg").size(240, 240).create()));
        educations.add(new StudentDemo("2", "江西科技师范大学", "201209", "201507", "hehe", Pictures.ofLocal(tempPathPrefix + "3.jpg").size(204, 204).create()));
//        for (int i = 3; i < 100; i++) {
//            educations.add(new StudentDemo(i + "", "江西科技师范大学" + i, "201209", "201507", "hehe", Pictures.ofLocal(tempPathPrefix + "3.jpg").size(204, 204).create()));
//        }
        data.put("educations", educations);
        data.put("educations1", educations);
        data.put("educations2", educations);
        //单个图片  本地图片
        data.put("image1", Pictures.ofLocal(tempPathPrefix + "2.png").size(420, 350).center().create());
        //单个图片  远程图片
        String webImageUrl = "https://trademark.zbjimg.com/pattern-prod/20200811/image_11/48277460.jpg";
        String webImageUrl1 = "https://trademark.zbjimg.com/pattern-prod/20200811/image_2/47539358.jpg";
        String webImageUrl2 = "https://trademark.zbjimg.com/pattern-prod/20190813/image_8/39878446.jpg";
        String webImageUrl3 = "https://trademark.zbjimg.com/pattern-prod/20201009/image_3/49473590.jpg";
        String webImageUrl4 = "https://trademark.zbjimg.com/pattern-prod/20190813/image_8/39878446.jpg";

        data.put("image2", Pictures.ofUrl(webImageUrl).size(420, 350).center().create());

        // 图片集合导出  二维数组
        List<ImageTemp> imageList = new ArrayList<ImageTemp>();
        imageList.add(new ImageTemp("问题一", "11111111", new ArrayList<Map<String, PictureRenderData>>() {{
            add(new HashMap<String, PictureRenderData>() {{
                put("image", Pictures.ofUrl(webImageUrl).size(420, 350).center().create());
            }});
            add(new HashMap<String, PictureRenderData>() {{
                put("image", Pictures.ofUrl(webImageUrl1).size(420, 350).center().create());
            }});
        }}));

        imageList.add(new ImageTemp("问题二", "22222222222", new ArrayList<Map<String, PictureRenderData>>() {{
            add(new HashMap<String, PictureRenderData>() {{
                put("image", Pictures.ofUrl(webImageUrl2).size(420, 350).center().create());
            }});
        }}));

        imageList.add(new ImageTemp("问题三", "333333333333", new ArrayList<Map<String, PictureRenderData>>() {{
            add(new HashMap<String, PictureRenderData>() {{
                put("image", Pictures.ofUrl(webImageUrl2).size(420, 350).center().create());
            }});
            add(new HashMap<String, PictureRenderData>() {{
                put("image", Pictures.ofUrl(webImageUrl3).size(420, 350).center().create());
            }});
            add(new HashMap<String, PictureRenderData>() {{
                put("image", Pictures.ofUrl(webImageUrl4).size(420, 350).center().create());
            }});
        }}));

        data.put("imageList", imageList);


        // 图片集合导出
        List<Map<String, PictureRenderData>> images = new ArrayList<Map<String, PictureRenderData>>();
        images.add(new HashMap<String, PictureRenderData>() {{
            put("image", Pictures.ofUrl(webImageUrl1).size(420, 350).center().create());
        }});
        images.add(new HashMap<String, PictureRenderData>() {{
            put("image", Pictures.ofUrl(webImageUrl2).size(420, 350).center().create());
        }});
        images.add(new HashMap<String, PictureRenderData>() {{
            put("image", Pictures.ofUrl(webImageUrl3).size(420, 350).center().create());
        }});
        images.add(new HashMap<String, PictureRenderData>() {{
            put("image", Pictures.ofUrl(webImageUrl4).size(420, 350).center().create());
        }});

        data.put("images", images);

        tempExportWorldSaveDisk(tempPath, "temp.docx", System.currentTimeMillis() + "_test", new String[]{"educations", "educations1", "educations2"}, data);


    }


    /**
     * 模板导出world ,切world转为pdf 文件存储到磁盘
     *
     * @param prefixPath  路径前缀 c:/
     * @param tempName    模板名称 temp.docx
     * @param outFileName 输出文件名称 安全风险
     * @param arrayNames  数组集合名称 ['list','list1']
     * @param data        数据 {"",""}
     * @return 返回文件存储绝对路径  {"world": worldFileFullPath, "pdf": pdfFileFullPath}
     * @throws IOException
     */
    public static Map tempExportWorldToPDFSaveDisk(String prefixPath, String tempName, String outFileName, String[] arrayNames, Map<String, Object> data) throws Exception {
        String worldFileFullPath = tempExportWorldSaveDisk(prefixPath, tempName, outFileName, arrayNames, data);
        String pdfFileFullPath = PDFUtil.word2Pdf2(worldFileFullPath, prefixPath + temporaryPathPDF, outFileName);
        return new HashMap() {{
            put("world", worldFileFullPath);
            put("pdf", pdfFileFullPath);
        }};
    }

    /**
     * 模板导出world  文件存储到磁盘
     *
     * @param prefixPath  路径前缀 c:/
     * @param tempName    模板名称 temp.docx
     * @param outFileName 输出文件名称 安全风险
     * @param arrayNames  数组集合名称 ['list','list1']
     * @param data        数据 {"",""}
     * @return 返回文件存储绝对路径
     * @throws IOException
     */
    public static String tempExportWorldSaveDisk(String prefixPath, String tempName, String outFileName, String[] arrayNames, Map<String, Object> data) throws IOException {
        // 获取world模板 绝对路径
        String tempFullPath = prefixPath + templatesPath + tempName;
        // 输出world文件 绝对路径
        String outFileFullPath = prefixPath + temporaryPath + outFileName + ".docx";
        File fileTemp = new File(tempFullPath);
        // 判断模板文件夹是否 不存在则创建
        if (!fileTemp.getParentFile().exists()) {
            fileTemp.getParentFile().mkdirs();
        }
        // 判断模板是否存在
        if (!fileTemp.exists()) {
            throw new RuntimeException("模板不存在");
        }
        // 判断文件输出文件夹是否 不存在则创建
        File outFile = new File(outFileFullPath);
        if (!outFile.getParentFile().exists()) {
            outFile.getParentFile().mkdirs();
        }
        XWPFTemplate template = null;
        if (arrayNames == null || arrayNames.length == 0) {
            // 没有集合数据
            template = XWPFTemplate.compile(tempFullPath).render(data);
        } else {
            // 有集合数据
            LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
            Configure config = Configure.builder().bind(policy, arrayNames).build();
            template = XWPFTemplate.compile(tempFullPath, config).render(data);
        }
        // 读取模板渲染参数
        try {
            template.writeToFile(outFileFullPath);
            template.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("outFileFullPath:>>>> " + outFileFullPath);
        return outFileFullPath;
    }

    /**
     * 模板导出world  文件直接通过 response 文件流输出给前端直接下载
     *
     * @param prefixPath 路径前缀
     * @param tempName   模板名称
     * @param arrayNames 数组集合名称
     * @param data       数据
     * @param response
     * @throws IOException
     */
    public static void tempExportWorldDownload(String prefixPath, String tempName, String[] arrayNames, Map<String, Object> data, HttpServletResponse response) throws IOException {
        String outFileName = System.currentTimeMillis() + "";
        tempExportWorldDownload(prefixPath, tempName, outFileName, arrayNames, data, response);
    }

    /**
     * @param prefixPath  路径前缀
     * @param tempName    模板名称
     * @param outFileName 输出文件名称
     * @param arrayNames  数组集合名称
     * @param data        数据
     * @param response
     * @throws IOException
     */
    public static void tempExportWorldDownload(String prefixPath, String tempName, String outFileName, String[] arrayNames, Map<String, Object> data, HttpServletResponse response) throws IOException {
        // 获取world模板 绝对路径
        String tempFullPath = prefixPath + templatesPath + tempName;
        // 判断模板文件夹是否 不存在则创建
        File fileTemp = new File(tempFullPath);
        if (!fileTemp.getParentFile().exists()) {
            fileTemp.getParentFile().mkdirs();
        }
        // 判断模板是否存在
        if (!fileTemp.exists()) {
            throw new RuntimeException("模板不存在");
        }
        XWPFTemplate template = null;
        if (arrayNames == null || arrayNames.length == 0) {
            // 没有集合数据
            template = XWPFTemplate.compile(tempFullPath).render(data);
        } else {
            // 有集合数据
            LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
            Configure config = Configure.builder().bind(policy, arrayNames).build();
            template = XWPFTemplate.compile(tempFullPath, config).render(data);
        }
        // 读取模板渲染参数
        try {
            //out为OutputStream，需要写出到的目标流
            //response为HttpServletResponse对象
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
            if (ObjectUtil.isEmpty(outFileName)) {
                outFileName = System.currentTimeMillis() + "";
            }
            response.setHeader("Content-Disposition", "attachment;filename=" + outFileName + ".docx");
            ServletOutputStream out = response.getOutputStream();
            template.write(out);
            //此处记得关闭输出Servlet流
            IoUtil.close(out);
            template.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
